package com.wuuxiang.i5xforyou.utils;

import java.io.UnsupportedEncodingException;
import java.util.Date;

import org.apache.commons.lang.time.DateUtils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

/** 
 * @ClassName: JwtUtil
 * @Description: JwtUtil
 * @author Mobile Web Group-lff
 * @date 2017年9月6日 下午5:52:56
 *
 */
public class JwtUtil {
	//暂时先去掉final 关键字，考虑是否将相关信息有配置中心读取
	private static String secret = "15foryou";
	private static String issuer = "wuuxiang";
	
	//超时时间设置
    public static long exp = 60 * 60 * 23 * 1000;
    //真实时间设置
    public static long realexp = 60 * 60 * 24 * 1000;
	
/*	//超时时间设置
    public static long exp = 30 * 1000;
    //真实时间设置
    public static long realexp = 60 * 1000;*/
	
	public static String createToken(String subject, Date expire) throws Exception {
		Algorithm algorithm = Algorithm.HMAC256(secret);
		String token = JWT.create()
			.withIssuer(issuer)
			.withSubject(subject)
			.withExpiresAt(expire)
			.sign(algorithm);
		
		return token;
	}
	
	public static String createToken(String subject) throws Exception {
		Algorithm algorithm = Algorithm.HMAC256(secret);
		String token = JWT.create()
			.withIssuer(issuer)
			.withSubject(subject)
			.withExpiresAt(new Date(System.currentTimeMillis() + realexp))
			.sign(algorithm);
		
		return token;
	}
	
	public static String verifyToken(String token) {
		String vesubject = "";
		try {
			Algorithm algorithm = Algorithm.HMAC256(secret);
			JWTVerifier verifier = JWT.require(algorithm)
				.withIssuer(issuer)
				.build(); //Reusable verifier instance
			DecodedJWT jwt = verifier.verify(token);
			vesubject = jwt.getSubject();
		} catch (UnsupportedEncodingException exception){
			//UnsupportedEncodingException
		} catch (JWTVerificationException exception){
			//JWTVerificationException
		}
		
		return vesubject;
	}
	
	
	public static void main(String[] args) throws Exception {
		
		String a =createToken("crm7", DateUtils.addHours(new Date(), 2));
		System.out.println(DateUtils.addHours(new Date(), 2).getTime() - new Date().getTime());
		System.out.println(a);
		System.out.println(verifyToken(a));
	}
}
